import KoaRouter from 'koa-router'
import { Models } from '../../../../common/typings/model'
import { Api } from '../../../../common/typings/api'
import Mysql from '../../../../core/Mysql'
import registerSchema from '../../../../common/apiValidate/system/auth/register'
import validator from '../../../../middlewares/validator'
import httpErrors from '../../../../core/HttpException'
import DateUtils from '../../../../common/utils/DateUtils'
import Config from '../../../../config/Config'

const router = new KoaRouter({
  prefix: `${Config.api_prefix}system/auth`,
})

/**
 * 邮箱注册，注册成功后，权限为NoVerifyEmail，并发送验证邮件，验证通过后权限为User
 */
router.post('/emailRegister', validator(registerSchema, 'body'), async (ctx: Models.Ctx) => {
  const { code, password, userName, email }: Api.User.Register.emailRegister = ctx.request
    .body as unknown as Api.User.Register.emailRegister
  if (ctx.session?.code !== code) {
    throw new httpErrors.ParameterException('验证码错误')
  }
  const date = DateUtils.format(new Date())

  // 注册
  await Mysql.command(`
        INSERT INTO user ( user_name, email, password, created_at, updated_at )
        VALUES
        ( '${userName}', '${email}', '${password}', '${userName}', '${date}', '${date}' );
    `)

  throw new httpErrors.Success()
})

export default router
